package array.leetcode.medium;

import java.util.Random;

/**
 * @author bruin_du
 * @description 按权重生成随机数
 * @date 2022/8/28 23:41
 **/
public class OfferII071_PickIndex {
    Random random = new Random();

    int[] prefix;
    int sum;

    public OfferII071_PickIndex(int[] w) {
        prefix = new int[w.length];
        for (int i = 0; i < w.length; i++) {
            sum += w[i];
            prefix[i] = sum;
        }
    }

    public int pickIndex() {
        int x = random.nextInt(sum) + 1;
        int left = 0, right = prefix.length - 1;
        while (left < right) {
            int mid = left + (right - left >> 1);
            if (prefix[mid] < x) left = mid + 1;
            else right = mid;
        }
        return left;
    }
}
